<template>
  <div class="relative page-container give-car-wrapper">
    <div class="page-form-block">
      <!-- 统计 -->
      <summary-info :summaryList="summaryLease" />
      <a-divider />
      <summary-info :summaryList="summaryMember">
        <template #memberName>
          {{ orderInfo.memberName }}
          <a-button
            size="mini"
            type="primary"
            style="margin-left: 10px"
            v-if="orderDetailGetted && (!memberInfo.driverFrontFileId || !memberInfo.driverReverseFileId)"
            @click="uploadDrivierFn"
          >
            未上传驾驶证
          </a-button>
          <a-button
            size="mini"
            type="primary"
            style="margin-left: 10px"
            v-if="orderDetailGetted && (!memberInfo.idCardFrontFileId || (memberInfo.cardType == 0 && !memberInfo.idCardReverseFileId))"
            @click="uploadIdCardFn"
          >
            未上传身份证明
          </a-button>
        </template>
      </summary-info>
    </div>
    <a-divider />
    <!-- 交车信息 -->
    <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
      <card title="交车信息" style="margin-top: 20px">
        <box-info :carId="orderInfo.carId" style="margin-bottom: 20px" />
        <page-form-row>
          <page-form-item label="交车里程" field="giveCarMileage">
            <i-input-number :precision="0" unit="公里" v-model="form.giveCarMileage" />
          </page-form-item>
          <page-form-item label="交车油(电)量" field="giveFuelNum">
            <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.giveFuelNum" />
          </page-form-item>
          <page-form-item field="giveStaffId" label="交车人">
            <remote-select
              v-model="form.giveStaffId"
              v-model:label="form.giveStaffName"
              :params="{
                oldId: defaultStaffId ? defaultStaffId : undefined,
                siteIdList: [orderInfo.siteId],
              }"
              type="staff_authOrg"
            />
          </page-form-item>
          <page-form-item field="giveCarTime" label="交车时间">
            <i-date-picker class="w-full" v-model="form.giveCarTime" showTime />
          </page-form-item>
          <page-form-item label="交车备注" size="2/3">
            <i-textarea v-model="form.useStartRemark" />
          </page-form-item>
          <page-form-item label="交车照片" size="1">
            <upload-img v-model="form.giveFileIds" />
          </page-form-item>
          <page-form-item label="交车视频" size="1" class="mb-0">
            <upload-video v-model="form.giveVideoFileIds" :max="1" />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
    <!-- 费用信息 -->
    <div class="relative fee-pane-content">
      <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
        <card toggle :toggleDefault="false" :showDivider="false">
          <template #title>交车费</template>
          <template v-for="(item, index) in feeForm.orderFee" :key="index">
            <fee-pane :orderFeeIndex="index" :disabledOnlineFee="orderInfo.orderSource == 1" />
          </template>
        </card>
      </page-form>
    </div>
  </div>
  <!-- 底部 footer -->
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
  <!-- 上传驾驶证照片 -->
  <upload-driver-license-modal ref="uploadDriverLicenseModalRef" @ok="uploadSuccessFn" />

  <!-- 上传身份证明照片 -->
  <upload-id-card-modal ref="uploadIdCardModalRef" @ok="uploadIdCardSuccessFn" />
</template>
<script setup name="LongOrderGiveCar">
  import { ref, provide, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import { getLongOrderDetails, giveCar } from '@/api/order/czsOrder'
  import feePane from './components/order-fee/fee-pane.vue'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from './components/order-fee/fee-utils.js'
  import uploadDriverLicenseModal from './components/upload-driver-license-modal.vue'
  import uploadIdCardModal from './components/upload-id-card-modal.vue'
  import iTextarea from '@/views/order/long-order/components/i-textarea.vue'
  import summaryInfo from './components/summary-info.vue'
  import boxInfo from '../../business/workOrder/order/components/box-modal.vue'
  import { handleContracList } from './utils'
  import useNavigate from '@/hooks/useNavigate'
  import dayjs from 'dayjs'
  import useUserStore from '@/store/modules/user'

  const { navigateBack } = useNavigate()
  const userStore = useUserStore()
  const route = useRoute()
  const orderId = route.params.id
  const orderInfo = ref({})
  const memberInfo = ref({})
  const orderDetailGetted = ref(false)

  const form = ref({
    id: orderId,
    giveCarTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    // 上传合同
    contractList: [],
  })

  // 处理默认值
  const rules = {
    giveStaffId: [{ required: true, message: '请选择交车人' }],
    useStartTime: [{ required: true, message: '请选择交车时间' }],
    giveCarMileage: [{ required: true, message: '请输入交车里程' }], // 交车里程
    giveFuelNum: [{ required: true, message: '请输入交车油(电)量' }], // 交车油(电)量
  }

  const formRef = ref()
  provide('form', form)

  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: `${orderInfoVal.expectedUseCarTime} - ${orderInfoVal.expectedReturnCarTime}`,
        },
        { label: '租期', value: orderInfoVal.leaseNumberStr },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '预订车型', value: orderInfoVal.originalModelName },
        { label: '交车车型', value: orderInfoVal.modelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.licenseNo }],
    ]
  })

  const summaryMember = computed(() => {
    const memberInfoVal = memberInfo.value
    const orderInfoVal = orderInfo.value
    return [
      orderInfoVal.clientId
        ? [
            { label: '承租人', slotName: 'memberName' },
            { label: '企业名称', value: orderInfoVal.clientName },
            { label: '证件类型', value: memberInfoVal.cardTypeName },
          ]
        : [
            { label: '承租人', slotName: 'memberName' },
            { label: '证件类型', value: memberInfoVal.cardTypeName },
          ],
      [
        { label: '联系电话', value: memberInfoVal.phone },
        { label: '证件号', value: memberInfoVal.cardNumber },
      ],
    ]
  })

  const priceTemplateId = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  const defaultStaffId = ref()
  if (orderId) {
    getLongOrderDetails({ id: orderId }).then((res) => {
      orderDetailGetted.value = true
      const result = res.result
      orderInfo.value = result.orderInfo
      memberInfo.value = result.memberInfoDto
      // 处理默认值
      // 车务专员 | 当前登录者 id
      defaultStaffId.value = orderInfo.value.giveStaffId || userStore.employeeId
      // 默认交车人
      form.value.giveStaffId = defaultStaffId.value
      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (storeTemplate, templateId) => {
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
      })
      // 合同信息处理
      if (orderInfo.value.contractList) {
        form.value.contractList = handleContracList(orderInfo.value.contractList)
      }
    })
  }

  // 上传驾驶证
  const uploadDriverLicenseModalRef = ref()
  const uploadDrivierFn = () => {
    uploadDriverLicenseModalRef.value.open(memberInfo.value.id, memberInfo.value.driverFrontFileId, memberInfo.value.driverReverseFileId)
  }
  // 上传完成
  // 更新驾驶证正反面信息
  const uploadSuccessFn = (info) => {
    memberInfo.value.driverFrontFileId = info.driverFrontFileId
    memberInfo.value.driverReverseFileId = info.driverReverseFileId
  }
  // 上传身份证明
  const uploadIdCardModalRef = ref()
  const uploadIdCardFn = () => {
    uploadIdCardModalRef.value.open(
      memberInfo.value.id,
      memberInfo.value.cardType,
      memberInfo.value.idCardFrontFileId,
      memberInfo.value.idCardReverseFileId
    )
  }
  // 上传完成
  // 更新身份证明正反面信息
  const uploadIdCardSuccessFn = (info) => {
    memberInfo.value.idCardFrontFileId = info.idCardFrontFileId
    memberInfo.value.idCardReverseFileId = info.idCardReverseFileId
  }
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true
        let feeFormValue = feeForm.value
        let costInfo = buildCostInfoParam(feeFormValue)
        // 合同信息

        const param = {
          ...form.value,
          orderFee: costInfo.orderFee[0],
        }
        giveCar(param)
          .then(() => {
            noticeSuccess()
            navigateBack()
          })
          .finally(() => (okLoading.value = false))
      }
    })
  }
</script>
<style lang="less" scoped>
  .contContainer {
    margin-top: 25px;
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
  }
</style>
